package genedit.gui;

import genedit.model.HierarchyElement;
import genedit.model.Workspace;
import genedit.model.graph.GraphElement;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;

/**
 * Klasa zadužena za implementaciju funkcionalnosti preimenovanja na dvoklik.
 * 
 * @author Nikola
 * @version 1.0 18/12/13
 */
public class GProjectTreeEditor extends DefaultTreeCellEditor implements ActionListener {

	private TreeNode stavka = null;
	private JTextField edit = null;

	public GProjectTreeEditor(JTree jt, DefaultTreeCellRenderer dftcr) {
		super(jt, dftcr);
	}

	public Component getTreeCellEditorComponent(JTree jt, Object he, boolean arg2, boolean arg3,
			boolean arg4, int arg5) {
		if (he instanceof Workspace)
			return null;

		stavka = (TreeNode) he;
		edit = new JTextField(he.toString());
		edit.addActionListener(this);
		return edit;
	}

	public boolean isCellEditable(EventObject e) {
		if (e instanceof MouseEvent)
			if (((MouseEvent) e).getClickCount() == 2) {
				return true;
			}
		return false;
	}

	public void actionPerformed(ActionEvent e) {
		if (!(stavka instanceof Workspace))
			if (stavka instanceof HierarchyElement)
				((HierarchyElement) stavka).rename(e.getActionCommand());
			else
				((GraphElement) stavka).setName(e.getActionCommand());

		SwingUtilities.updateComponentTreeUI(GProjectTree.getInstance().getTree());
	}
}
